/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package pt.iasd.youthshelter.activity.nodes;

import java.awt.event.ActionEvent;
import java.util.Collection;
import java.util.List;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.AbstractAction;
import javax.swing.Action;
import static javax.swing.Action.NAME;
import org.netbeans.api.progress.ProgressHandle;
import org.netbeans.api.progress.ProgressHandleFactory;
import org.openide.DialogDisplayer;
import org.openide.NotifyDescriptor;
import org.openide.nodes.AbstractNode;
import org.openide.nodes.Children;
import org.openide.util.Lookup;
import org.openide.util.Lookup.Result;
import org.openide.util.LookupEvent;
import org.openide.util.LookupListener;
import org.openide.windows.TopComponent;
import pt.iasd.youthshelter.activity.ActivityEditorTopComponent;
import pt.iasd.youthshelter.activity.ListSorter;
import pt.iasd.youthshelter.datacore.events.ActivityRefreshEvent;
import pt.iasd.youthshelter.datamodel.Activity;
import pt.iasd.youthshelter.datamodel.service.ActivityController;
import pt.iasd.youthshelter.logging.ILoggingService;

/**
 *
 * @author Rui
 */
public class RootNode extends AbstractNode implements LookupListener {
    private static final ResourceBundle bundle = java.util.ResourceBundle.getBundle("pt/iasd/youthshelter/activity/Bundle");
    private final Result<ActivityRefreshEvent> lookupResult;

    /** Creates a new instance of RootNode */
    public RootNode(Children children) {
        super(children);
        ActivityController controller = Lookup.getDefault().lookup(ActivityController.class);
        if(controller != null) {
            lookupResult = controller.getLookup().lookupResult(ActivityRefreshEvent.class);
            lookupResult.addLookupListener(this);
        } else {
            lookupResult = null;
            Lookup.getDefault().lookup(ILoggingService.class).warn(this.getClass(),
                    "Global lookup found no activity controller object registered.");
        }
    }

    @Override
    public Action getPreferredAction() {
        return new NewActivityAction();
    }

    @Override
    public Action[] getActions(boolean context) {
        return new Action[]{new NewActivityAction(), new RefreshListAction()};
    }

    @Override
    public void resultChanged(LookupEvent event) {
        Lookup.Result result = (Lookup.Result) event.getSource();
        Collection coll = result.allInstances();
        for (Object object : coll) {
            if (object instanceof ActivityRefreshEvent){
                (new RefreshListAction()).actionPerformed(null);
            }
        }
    }
    
    private class NewActivityAction extends AbstractAction {
        public NewActivityAction() {
            putValue(NAME, bundle.getString("Action.New"));
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            NotifyDescriptor.InputLine input = new NotifyDescriptor.InputLine(
                bundle.getString("Input.Activity.Name"),
                bundle.getString("Input.Activity.Title")
            );
            if(DialogDisplayer.getDefault().notify(input) == NotifyDescriptor.OK_OPTION
                && input.getInputText() != null && !input.getInputText().isEmpty()) {
                TopComponent editor = new ActivityEditorTopComponent(input.getInputText());
                editor.open();
                editor.requestActive();
            }
        }
    }
    
    private class RefreshListAction extends AbstractAction {
        public RefreshListAction() {
            putValue(NAME, bundle.getString("Action.Refresh"));
        }
        
        @Override
        public void actionPerformed(ActionEvent e) {
            List<Activity> activities = null;
            ProgressHandle pHandle = ProgressHandleFactory.createHandle(
                    bundle.getString("ProgressBarLoad"));
            ActivityController controller = Lookup.getDefault().lookup(ActivityController.class);
            if(controller != null) {
                pHandle.start();
                try {
                    activities = ListSorter.sortActivitiesByName(controller.findCurrentActivityEntities());
                } catch(Exception ex) {
                    Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, ex.getLocalizedMessage(), ex);
                    pHandle.finish();
                }
                setChildren(new ActivityChildren(activities));
                pHandle.finish();
            }
        }
    }
}
